package com.allen.excelUtils.column;

import java.util.HashMap;
import java.util.Map;

import org.apache.poi.ss.usermodel.Row;

import com.allen.excelUtils.ExcelConfig;



public class ColumnMapping {
   private ExcelConfig config;
   private Map<String,Column> colMap = new HashMap<String, Column>();//记录名称与索引的映射关系
   
   public ColumnMapping(){
	   config = new ExcelConfig();
   }
   public ColumnMapping(ExcelConfig config) {
	 this.config = config;
   }
   
   /**
    * 根据第一行构建映射列表
    * @param row
    */
   public void init(Row row){
	   if (null != row) {
		   String cell =null;
		 for (int colIndex = 0; colIndex < row.getLastCellNum(); colIndex++) {
			 cell = row.getCell(colIndex).getStringCellValue();
			 for (Column column : config.getColumns()) {
				if (cell.equals(column.getAlias())) {
					column.setIndex(colIndex);
					colMap.put(column.getName(), column);
				}
			}
		 }
	   }else {
		throw new NullPointerException("若选择按第一行匹配,那么excel第一行不能为空。");
	 }
   }
   
   /**
    * 简单建立列名和其索引映射
    */
	public void init() {
		int index = 0;
        for (Column column : config.getColumns()) {
        	column.setIndex(index);
        	colMap.put(column.getName(), column);
        	index++;
		}
	}
   
   public int getColumnIndexByName(String name)throws IndexOutOfBoundsException { 
	    return colMap.get(name).getIndex();
   }

	public Map<String, Column> getColMap() {
		return colMap;
	}
}
